﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

namespace BToolkit
{
    public class UIVisibleByTouch : MonoBehaviour
    {
        public Transform[] buttons;
        private float[] alphas;
        private const float ShowDuration = 2;
        private bool isShow;
        UIVisibleByTouch previousTouchShowBtnsCtrl;
        static UIVisibleByTouch CurrTopCtrl;

        void Awake()
        {
            alphas = new float[buttons.Length];
            for (int i = 0; i < alphas.Length; i++)
            {
                Transform btns = buttons[i];
                if (btns)
                {
                    if (btns.GetComponent<Image>())
                    {
                        alphas[i] = btns.GetComponent<Image>().color.a;
                    }
                    else
                    {
                        alphas[i] = btns.GetComponent<RawImage>().color.a;
                    }
                }
            }
            previousTouchShowBtnsCtrl = CurrTopCtrl;
        }

        void OnEnable()
        {
            CurrTopCtrl = this;
        }

        void OnDisable()
        {
            if (CurrTopCtrl == this)
            {
                CurrTopCtrl = previousTouchShowBtnsCtrl;
            }
        }

        IEnumerator Start()
        {
            yield return new WaitForSeconds(ShowDuration);
            isShow = false;
            for (int i = 0; i < buttons.Length; i++)
            {
                Transform btn = buttons[i];
                if (btn)
                {
                    btn.DOAlpha(0, 2, Ease.OutExpo).OnComplete(() =>
                    {
                        TargetShow(btn, false);
                    });
                }
            }
        }

        void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                if (CurrTopCtrl != this)
                {
                    return;
                }
                if (!isShow)
                {
                    isShow = true;
                    for (int i = 0; i < buttons.Length; i++)
                    {
                        Transform btn = buttons[i];
                        if (btn)
                        {
                            TargetShow(btn, true);
                            btn.DOAlpha(alphas[i]);
                        }
                    }
                    StartCoroutine(Start());
                }
            }
        }

        void TargetShow(Transform target, bool b)
        {
            Image img = target.GetComponent<Image>();
            if (img)
            {
                img.enabled = b;
            }
            else
            {
                RawImage rawimg = target.GetComponent<RawImage>();
                if (rawimg)
                {
                    rawimg.enabled = b;
                }
            }
        }
    }
}